import configparser
from threading import Lock
from typing import List
from datetime import datetime
from mysql.connector import pooling
import calendar

import mysql.connector
import logging

lock = Lock()

class ImageDB:
    """
    用来处理拍摄设备(手机)数据
    """

    def __init__(self, db_config,line_name,  line_token):
        self.config = db_config
        self.line_name = line_name
        self.line_token = line_token
        self.pool:pooling.MySQLConnectionPool = None

    def connect(self):
        try:
            prefix = self.line_token.split("-")[0]
            self.pool = pooling.MySQLConnectionPool(pool_name=f"{prefix}_image_pool", pool_size=8, **self.config)
            print("image_pool database connect success")
        except Exception as e:
            print(f"image_pool database connect failed: {e}")
            raise Exception("image_pool 数据库无法连接")

    def get_connection(self):
        return self.pool.get_connection()

    def get_cursor(self, conn, dictionary=None):
        return conn.cursor(dictionary=dictionary)

    def find_flaw_data(self, start_pId, end_pId):
        conn = self.get_connection()
        with lock:
            cursor = self.get_cursor(conn, True)
            self.execute(cursor, f" SELECT * from workshop1_l1产线_product_flaw_record where product_id > {start_pId} and product_id < {end_pId} and inspection_state=2")
            result = cursor.fetchall()
            cursor.close()
            conn.commit()
            self.close_conn(conn)
            if result is None:
                return None
            return result
        pass

    def find_flaw_imgs_data(self, start_pId, end_pId):
        """ 根据机位ID和图片ID, 查询已有的图片信息 """
        conn = self.get_connection()
        with lock:
            cursor = self.get_cursor(conn, True)
            self.execute(cursor, f"SELECT * from imgs_l1产线_2024_7 where product_id > {start_pId} and  product_id < {end_pId}  ")
            result = cursor.fetchall()
            cursor.close()
            conn.commit()
            self.close_conn(conn)
            if result is None:
                return None
            return result




    def close_conn(self , conn):
        if conn is not None:
            conn.close()

    def close(self):
        if self.pool:
            self.pool._remove_connections()

    def execute(self, cursor, sql):
        try:
            cursor.execute(sql)
        except Exception as e:
            pass

